package co.gov.medellin.ssti.sub.paoyer.administration.util;

import org.apache.struts.action.ActionMapping;

import co.gov.medellin.ssti.sub.paoyer.administration.exception.AdministrationUserException;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;
import co.gov.medellin.ssti.sub.paoyer.common.exception.CommonUserException;
import co.gov.medellin.ssti.sub.paoyer.common.exception.UserException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Vector;

public class AccessControl {
	public AccessControl() {
	}

	public void validateAccess(ActionMapping mapping,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, UserException {
		if (request.getSession().getAttribute("userInfo") == null) {
			throw new UserException(
					new AdministrationUserException().getModuleVO(),
					AdministrationUserException.ENDED_SESSION);
		}

		String path = mapping.getPath();
		UserVO user = (UserVO) request.getSession().getAttribute("userInfo");
		Vector activeResources = new Vector(user.getResources());

		int verify = activeResources.indexOf(path);
		if (verify == -1) {
			throw new UserException(new CommonUserException().getModuleVO(),
					CommonUserException.NOT_ALLOWED_RESOURCE);

		}

	}

	public void validateAccess(String path, HttpServletRequest request,
			HttpServletResponse response) throws IOException, UserException {
		if (request.getSession().getAttribute("userInfo") == null) {
			throw new UserException(
					new AdministrationUserException().getModuleVO(),
					AdministrationUserException.ENDED_SESSION);
		}

		UserVO user = (UserVO) request.getSession().getAttribute("userInfo");
		Vector activeResources = new Vector(user.getResources());
		int verify = activeResources.indexOf(path);
		if (verify == -1) {
			throw new UserException(new CommonUserException().getModuleVO(),
					CommonUserException.NOT_ALLOWED_RESOURCE);
		}

	}
}